/** 
Copyright (c) 2010, Sheikh Abdul Wahid Ahmed
Details @ http://extremecodeworld.codeplex.com/license
**/

using System;
using System.Data;
using System.Text; 
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using EXtremecode.PresentationLayer;

public partial class ASCXTextCombo : System.Web.UI.UserControl, IASCXControl
{

    private bool isSetDisplayMethodCalled = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        
    }

    public override string ClientID
    {
        get
        {
            return CurrentClientId; 
        }
    }
    
    protected void Page_PreRender(object sender, EventArgs e)
    {
        vldrRequired.ErrorMessage = string.Format("{0} : {1}",
            caption, ResourceProvider.GetGeneralResourceString("Message_FieldRequired"));

        if (DuplicateCheck && !IsReadOnly)
        {
            vldrDuplicate.Enabled = true;
            vldrDuplicate.ErrorMessage = string.Format("{0} : {1}",
                caption, ResourceProvider.GetGeneralResourceString("Message_Duplicate"));
            vldrDuplicate.Attributes.Add("ControlId", this.ClientID);

            textBox.Attributes.Add("onchange",textBox.Attributes["onchange"] + "this.CurrentCtrl.ValidateDuplicate()");
        }

        vldrCustom.ErrorMessage = string.Format("{0} : {1}",
            caption, ResourceProvider.GetGeneralResourceString("Message_ValueNotFound"));
        vldrCustom.Attributes.Add("ControlId", this.ClientID);
 
        //for openning popup
        string openningPopup = string.Format("OpenPopup('{0}',{1},{2},'{3}','{4}','{5}OnPopupValueReturn','{6}',escape('{7}'.Format(this.CurrentCtrl.GetValue())),'0');",
            popupURL,
            (popupWidth != null) ? popupWidth.Value.ToString() : "null",
            (popupHeight != null) ? popupHeight.Value.ToString() : "null",
            popupId,
            keyField,
            CurrentClientId,
            keyField,searchFormat);


        Image imgConrol = (IsReadOnly) ? imgNearLabel : imgNearTextBox;
        imgConrol.Attributes.Add("onclick", openningPopup);    

        
        //Regex validator.
        if (string.IsNullOrEmpty(vldrRegx.ErrorMessage))
        {
            vldrRegx.ErrorMessage = string.Format("{0} : {1}",
                caption, ResourceProvider.GetGeneralResourceString("Message_InvalidValue"));
        }
        if (string.IsNullOrEmpty(vldrRegx.ValidationExpression))
        {
            vldrRegx.ValidationExpression = ResourceProvider.GetExpression("Expression_NormalText");
        }


        //Script block
        string currentClientId=this.CurrentClientId;
        string originalClientId=this.OriginalClientId;
        string inputClientId=this.InputClientId;
        string displayClientId=this.DisplayClientId;

        StringBuilder sbScriptBlock = new StringBuilder();

        sbScriptBlock.AppendLine("<script>");

        //succeeded callback function.
        sbScriptBlock.AppendLine(string.Format("function {0}SucceededCallback(info){{" + Environment.NewLine +
            "if(info == null){{" + Environment.NewLine + 
            "{0}.IsValueFound = false;info='';" + Environment.NewLine +
            "}}else{{" + Environment.NewLine +
            "{0}.IsValueFound = true;" + Environment.NewLine + 
            "}}" + Environment.NewLine + 
            "if({0}.DisplayCtrl != null){{" + Environment.NewLine +
            " {0}.DisplayCtrl.innerHTML = {0}.StringFromat.Format(info);" + Environment.NewLine +
            "}}" + Environment.NewLine + 
            "if({0}.OnSucceededHandler != null){{" + Environment.NewLine +
            "   {0}.OnSucceededHandler(info);" + Environment.NewLine +
            "}}" + Environment.NewLine +
            "}}",currentClientId));

        //On popup value return function
        sbScriptBlock.AppendLine(string.Format("function {0}OnPopupValueReturn(value){{" + Environment.NewLine +
            "{0}.SetValue(value);" + Environment.NewLine +
            "if({0}.ValidateDuplicate != null){0}.ValidateDuplicate();" + Environment.NewLine +
            "}}", currentClientId));

 
        sbScriptBlock.AppendLine(
            string.Format("var {0} = document.getElementById('{0}');",currentClientId));
        
        sbScriptBlock.AppendLine(
            string.Format("{0}.OriginalCtrl = document.getElementById('{1}');",
                currentClientId,originalClientId));

        sbScriptBlock.AppendLine(
            string.Format("{0}.ImageCtrl = document.getElementById('{1}');",
                currentClientId, imgConrol.ClientID));
        
        //img control requires current control reference.
        sbScriptBlock.AppendLine(
            string.Format("{0}.ImageCtrl.CurrentCtrl = {0};", currentClientId));

        sbScriptBlock.AppendLine(
            string.Format("{0}.InputCtrl = document.getElementById('{1}');",
            currentClientId,inputClientId));
        //input control requires current control reference.
        if (!IsReadOnly)
        {
            sbScriptBlock.AppendLine(
                string.Format("{0}.InputCtrl.CurrentCtrl = {0};", currentClientId));
        }
        
        sbScriptBlock.AppendLine(
            string.Format("{0}.DisplayCtrl = document.getElementById('{1}');",
            currentClientId,displayClientId));
        
        sbScriptBlock.AppendLine(
            string.Format("{0}.FormattingObject = new EmptyClass();",currentClientId));

        sbScriptBlock.AppendLine(
            string.Format("{0}.StringFromat = '{1}';", currentClientId,stringFormat));
        
        //these are required for webservice calling.
        sbScriptBlock.AppendLine(
            string.Format("{0}.EntityName = '{1}';", currentClientId, entityName));

        sbScriptBlock.AppendLine(
            string.Format("{0}.Key = '{1}';", currentClientId, keyField));
        

        sbScriptBlock.AppendLine(
            string.Format("{0}.FieldNames = '{1}';",
            currentClientId, displayFieldList));

        //for dupplication check
        if (DuplicateCheck && !IsReadOnly)
        {
            sbScriptBlock.AppendLine(
                string.Format("{0}.EntityNameDuplicateCheck = '{1}';", currentClientId, entityNameDuplicateCheck));

            sbScriptBlock.AppendLine(
                string.Format("{0}.FieldNameDuplicateCheck = '{1}';",
                currentClientId, fieldNameDuplicateCheck));

            sbScriptBlock.AppendLine(
                string.Format("{0}.ValidateDuplicate = ValidateDuplicate;",
                currentClientId, fieldNameDuplicateCheck));

            sbScriptBlock.AppendLine(
         string.Format("{0}.DuplicateStatusCtrl = document.getElementById('{1}');",
         currentClientId, hdnDuplicateStatus.ClientID));
        }


        //means it will be validated only when value changed on client site.
        sbScriptBlock.AppendLine(
           string.Format("{0}.IsValueFound = true;",
           currentClientId));


        //this need to be used, because popup may has extra filter and this filter
        //should be passed to webService when no involvement of Popup to be.
        sbScriptBlock.AppendLine(
            string.Format("{0}.WhereClause = '{1}';",
            currentClientId, whereClause));
        
        
        sbScriptBlock.AppendLine(
           string.Format("{0}.SucceededCallback = {0}SucceededCallback;",
           currentClientId));

        sbScriptBlock.AppendLine(
           string.Format("{0}.ErrorCallback = {1};",
           currentClientId, "errorCallback"));

        sbScriptBlock.AppendLine(
            string.Format("{0}.SetValue = SetComboTextValue;",currentClientId));

        sbScriptBlock.AppendLine(
            string.Format("{0}.GetValue = GetTextValue;",currentClientId));

        sbScriptBlock.AppendLine(
            string.Format("{0}.ResetValue = resetValue;", currentClientId));

        if (!string.IsNullOrEmpty(onSucceededHandler))
        {
            sbScriptBlock.AppendLine(
            string.Format("{0}.OnSucceededHandler = {1};", currentClientId,onSucceededHandler));
        }
        sbScriptBlock.AppendLine("</script>");
        scriptBlockLiteral.Text = sbScriptBlock.ToString();
        if (!isSetDisplayMethodCalled)
        {
            SetDisplay();
        }

    }

    private void SetDisplay()
    {
        
        if (IsReadOnly)
        {
            label.Text = Text;
        }
    }

    public string Value
    {
        get
        {
            string val = (isReadOnly && string.IsNullOrEmpty(textBox.Text)) ? hdnCurrent.Value : textBox.Text;

            return (val == string.Empty && isEmptyMeansNull) ?
                 null :
                 val;
        }
        set
        {
            textBox.Text = 
                hdnCurrent.Value = 
                hdnOriginal.Value = string.Empty;
            if (value != null)
            {
                textBox.Text =
                    hdnCurrent.Value =
                    hdnOriginal.Value = value;
            }


            SetDisplay();
            isSetDisplayMethodCalled = true;
        }
    }
    public string OriginalValue
    {
        get
        {
            string val = hdnOriginal.Value;
            return (val == string.Empty && isEmptyMeansNull) ?
                 null :
                 val;
        }
    }

    private bool isEmptyMeansNull = true;
    public bool IsEmptyMeansNull
    {
        get { return isEmptyMeansNull; }
        set { isEmptyMeansNull = value; }
    }

    public int MaxLength
    {
        get
        {
            return textBox.MaxLength;
        }
        set
        {
            textBox.MaxLength = value;
        }
    }

    public string Expression
    {
        get
        {
            return vldrRegx.ValidationExpression;
        }
        set
        {
            vldrRegx.ValidationExpression = value;
        }
    }

    public string ErrorMessage
    {
        get
        {
            return vldrRegx.ErrorMessage;
        }
        set
        {
            vldrRegx.ErrorMessage = value;
        }
    }

    private string entityName = string.Empty;
    public string EntityName
    {
        get
        {
            return entityName;
        }
        set
        {
            entityName = value;
        }
    }

    private string whereClause = string.Empty;
    public string WhareClause
    {
        get
        {
            return whereClause;
        }
        set
        {
            whereClause = value;
        }
    }

    private string onSucceededHandler = string.Empty;
    public string OnSucceededHandler
    {
        get
        {
            return onSucceededHandler;
        }
        set
        {
            onSucceededHandler = value;
        }
    }

    private string popupURL = string.Empty;
    public string PopupURL
    {
        get
        {
            return popupURL;
        }
        set
        {
            popupURL = value;
        }
    }

    private string popupId = string.Empty;
    public string PopupId
    {
        get
        {
            return popupId;
        }
        set
        {
            popupId = value;
        }
    }

    private int? popupWidth;
    public int? PopupWidth
    {
        get
        {
            return popupWidth;
        }
        set
        {
            popupWidth = value;
        }
    }

    private int? popupHeight;
    public int? PopupHeight
    {
        get
        {
            return popupHeight;
        }
        set
        {
            popupHeight = value;
        }
    }

    private string displayFieldList = string.Empty;
    public string DisplayFieldList
    {
        get
        {
            return displayFieldList;
        }
        set
        {
            displayFieldList = value;
        }
    }

    private string stringFormat = string.Empty;
    public string StringFormat
    {
        get
        {
            return stringFormat;
        }
        set
        {
            stringFormat = value;
        }
    }

    private string keyField = string.Empty;
    public string KeyField
    {
        get
        {
            return keyField;
        }
        set
        {
            keyField = value;
        }
    }

    private string searchFormat = "{0}";
    public string SearchFormat
    {
        get
        {
            return searchFormat;
        }
        set
        {
            searchFormat = value;
        }
    }


    #region IASCXControl Members

    public string DisplayCssClass
    {
        get
        {
           return label.CssClass;
        }
        set
        {
            label.CssClass = value;
        }
    }

    private bool isReadOnly = false;
    public bool IsReadOnly
    {
        get
        {
            return isReadOnly;
        }
        set
        {
            isReadOnly = value;
            if (isReadOnly)
            {
                              
                multiView.SetActiveView(viewReadOnly);
            }
            else
            {
                multiView.SetActiveView(viewEditable);
            }
        }
    }

    object IASCXControl.Value
    {
        get
        {
            return Value;
        }
        set
        {
            Value = value as string;
        }
    }
    object IASCXControl.OriginalValue
    {
        get
        {
            return OriginalValue;
        }
        
    }
    public bool HasValueChanged
    {
        get
        {
            return (Value != OriginalValue);
        }
    }

    public string Text
    {
        get
        {
            string val = Value;
            string str = string.Empty;
            if (val != null)
            {
                EXtremecode.WebServices.AWWebService service = new EXtremecode.WebServices.AWWebService();
                str =
                    string.Format(stringFormat,
                        service.GetFieldValues_WithFilter(entityName,
                        displayFieldList,
                        keyField, val, whereClause));

               
            }
            return str;
            
        }
    }

    public string OriginalClientId
    {
        get
        {
            return hdnOriginal.ClientID;
        }
    }
    public string CurrentClientId
    {
        get
        {
            return hdnCurrent.ClientID;
        }
    }
    public string InputClientId
    {
        get
        {
            return textBox.ClientID;
        }
    }
    public string InputUniqueId
    {
        get
        {
            return textBox.UniqueID;
        }
    }
    public string DisplayClientId
    {
        get
        {
            return label.ClientID;
        }
    }
    public string DisplayUniqueId
    {
        get
        {
            return label.UniqueID;
        }
    }

    public Control InputControl
    {
        get
        {
            return textBox;
        }
    }

    public string JSResetFunction
    {
        get
        {
            return "ResetTextBox";
        }
    }

    private bool isRequired = false;
    public bool IsRequired
    {
        get
        {
            return isRequired;
        }
        set
        {
            isRequired = value;

            if (isRequired)
            {
                textBox.CssClass = "requiredField";
                vldrRequired.Enabled = true;
                vldrRequired.Display = ValidatorDisplay.Dynamic;
            }
            else
            {
                textBox.CssClass = "";
                vldrRequired.Enabled = false;
                vldrRequired.Display = ValidatorDisplay.None;
            }
        }
    }

    private string caption = string.Empty;
    public string Caption
    {
        get
        {
            return caption;
        }
        set
        {
            caption = value;
        }
    }

    #endregion


    private bool duplicateCheck = false;
    public bool DuplicateCheck
    {
        get
        {
            return duplicateCheck;
        }
        set
        {
            duplicateCheck = value;
        }
    }


    private string fieldNameDuplicateCheck = string.Empty;
    public string FieldNameDuplicateCheck
    {
        get
        {
            return fieldNameDuplicateCheck;
        }
        set
        {
            fieldNameDuplicateCheck = value;
        }
    }

    private string entityNameDuplicateCheck = string.Empty;
    public string EntityNameDuplicateCheck
    {
        get
        {
            return entityNameDuplicateCheck;
        }
        set
        {
            entityNameDuplicateCheck = value;
        }
    }


    
}
